package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.lang.invoke.VarHandle;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    //存储context与servletmapper的关系如：localhost_8080_context -> servletmapper(name->sevlet)
    private Map<String, HttpServlet> servletMapper= new HashMap();

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
//TODO
//        解析server.xml生成host相关对象
//        根据appbase找应用目录
//        遍历解析各应用目录下的web.xml，
//        loadServlet
//        每个context对应一个servletMap，封装到host对象
//        初始化contextMapper

        Service service = parseServerConfig();

        String strPort = service.getConnectors().get(0).getPort();

        for(Container container : service.getContainers()){
            List<Engine> engines = container.getEngines();
            for(Engine engine : engines){
                List<Host> hosts = engine.getHosts();
                for(Host host : hosts){
                    parseWebConfig(host);
                }
            }
        }

        getServletMap(service);


        // 加载解析相关的配置，web.xml
//        loadServlet();


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(Integer.parseInt(strPort));
        System.out.println("=====>>>Minicat start on port：" + strPort);

        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/


        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/



        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }



    }


    //解析Service对象 将映射关系添加到servletMapper
    private void getServletMap(Service service) {
        final Connector connector = service.getConnectors().get(0);
        List<Container> containers = service.getContainers();
        for(Container container : containers) {
            List<Engine> engines = container.getEngines();

            for(Engine engine : engines){
                List<Host> hosts = engine.getHosts();
                for(Host host : hosts){
                    List<Context> contexts = host.getContexts();
                    for(Context context : contexts){
                        List<Wapper> wappers = context.getWappers();
                        for(Wapper wapper : wappers){
                            StringBuilder key = new StringBuilder();
                            key.append(host.getName()).append("_")
                                    .append(connector.getPort()).append("/")
                                    .append(context.getPath())
                                    .append(wapper.getServletMapping());
                            servletMapper.put(key.toString(), wapper.getServlet());
                        }
                    }
                }
            }
        }
    }

    //解析web.xml
    private void parseWebConfig(Host host) throws FileNotFoundException {
        String appBase = host.getAppBase();

        File file = new File(appBase);
        if(!file.exists()){
            throw new RuntimeException("appBase not found! appBase=" + appBase);
        }

        String[] list = file.list();
        for(String projectName : list){
            Context context = null;
            if(host.getContexts().isEmpty()){
                //没有单独配置context
                context = new Context(projectName);
                host.getContexts().add(context);
            } else {
                //TODO 有单独配置的context的情况在此实现
            }


            File projects = new File(appBase + "/" + projectName);
            String[] projectFileNames = projects.list();
            for(String name : projectFileNames){
                if("WEB-INF".equals(name)){
                    String webXmlfullPath = appBase  + "/" + projectName + "/WEB-INF/web.xml";
                    File file1 = new File(webXmlfullPath);
                    if(!file1.exists()){
                        throw new RuntimeException("web.xml not exist! filepath=" + appBase +"/WEB-INF/web.xml");
                    }
                    loadServlet(context, webXmlfullPath);
                }
            }
        }
    }

    private Service parseServerConfig() throws DocumentException {

        InputStream resourceAsStream = Bootstrap.class.getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(resourceAsStream);
        Element rootElement = read.getRootElement();

        List<Element> serviceEls = rootElement.selectNodes("//Service");
        Service service = null;
        for(Element serviceEl : serviceEls){

            service = new Service();

            String port = "";
            List<Element> connectors = serviceEl.selectNodes("Connector");
            for(Element connectorEl : connectors){
                port = connectorEl.attributeValue("port");
                service.getConnectors().add(new Connector(port));
            }


            List<Element> engines = serviceEl.selectNodes("Engine");
            for(Element engine : engines){
                List<Element> hosts = engine.selectNodes("Host");
                for(Element host : hosts){
                    String name = host.attributeValue("name");
                    String appBase = host.attributeValue("appBase");


                    Host hostConfig = new Host(name, appBase);
                    Engine engine1 = new Engine();
                    engine1.getHosts().add(hostConfig);

                    Container container = new Container();
                    container.getEngines().add(engine1);

                    List<Container> containers = service.getContainers();
                    containers.add(container);

                    List list = host.selectNodes("Context");
                    if(list != null){
                       //TODO 如果有配置context的话 解析context配置
                    }
                }
            }
        }

        return service;
    }

    private Mapper mapper = null;

//    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();

    //解析server.xml为mapper对象
    String  serverXmlPath = "";
//    parseServerXml



    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(Context context, String path) throws FileNotFoundException {
        InputStream resourceAsStream = new FileInputStream(path);
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                HttpServlet servlet = (HttpServlet) Class.forName(servletClass).newInstance();
//                servletMap.put(urlPattern, servlet);
                context.getWappers().add(new Wapper(urlPattern, servlet));
            }



        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
